在Day 3 - 如何運用 Laravel 框架設計模式規劃大型專案,當中提到Controller-Service-Repository的溝通,今天會介紹到底如何撰寫.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'user_id',
'title',
'content'
];
/**
* 將資料作轉換
*
* @var array
*/
protected $casts = [
'created_at' => 'datetime:Y-m-d H:i:s',
'updated_at' => 'datetime:Y-m-d H:i:s'
];
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id')->comment('發文者');
$table->string('title')->unique()->comment('標題');
$table->string('content')->comment('內文');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
$ sail artisan make:controller PostController
$ sail artisan make:service PostService
$ sail artisan make:repository PostRepository
routes/api.php
,讓我們能透過路由對應到指定的Controller
jwt.auth
的Group當中,這麼一來我們就能確保沒經過身份驗證的使用者無法建立文章.<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
Route::middleware(['jwt.auth'])->group(function () {
Route::group(['prefix' => 'post'], function () {
Route::post('/', [PostController::class, 'create']);
});
});
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\PostService;
use Illuminate\Http\JsonResponse;
class PostController extends Controller
{
protected $service;
public function __construct(PostService $service)
{
$this->service = $service;
}
/**
* 建立文章
* @param Request $request
* @return JsonResponse
*/
public function create(Request $request): JsonResponse
{
$result = $this->service->create($request->all());
return response()->json($result);
}
}
<?php
namespace App\Services;
use Yish\Generators\Foundation\Service\Service;
use App\Repositories\PostRepository;
use Illuminate\Support\Arr;
class PostService
{
/**
* @var PostRepository
*/
protected $post_repository;
public function __construct(PostRepository $post_repository)
{
$this->post_repository = $post_repository;
}
/**
* 建立文章
* @param array $data
* @return mixed
*/
public function create(array $data)
{
$title = Arr::get($data, 'title');
$content = Arr::get($data, 'content');
$post = $this->post_repository->createPost($title, $content);
return $post;
}
}
Auth::guard('api')->user()
來取得User model,藉此可以知道發文者的user_id<?php
namespace App\Repositories;
use App\Models\Post;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Auth;
class PostRepository
{
/**
* 建立文章
*
* @param string $title 標題
* @param string $content 內文
* @return mixed
*/
public function createPost(string $title, string $content)
{
try {
$user = Auth::guard('api')->user();
$post = new Post();
$post->title = $title;
$post->content = $content;
$post->user_id = $user->id;
$post->save();
return $post;
} catch (Exception $e) {
dd($e);
}
}
}
上述都建立完後,我們就可以透過Postman Call API來建立新的文章
如此一來就簡單快速的完成了發布文章的API,接下來文章會介紹寫Request validation與Error handler來優化我們的API.